package com.yonyou.crm.common.security.util;

import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;



public class Base64DesEncrypt implements IEncryption {
	
	 private static Base64DesEncrypt inst = null;
	 
	 private static final String DES_KEY = "12345678;"; 
	 
//	 private static final byte[] DES_IV = {(byte)0x12, (byte)0x34, (byte)0x56, (byte)0x78, (byte)0x90, (byte)0xAB, (byte)0xCD, (byte)0xEF};
	 private static final byte[] DES_IV = {(byte)0x31, (byte)0x32, (byte)0x33, (byte)0x34, (byte)0x35, (byte)0x36, (byte)0x37, (byte)0x38};
	 
	 private AlgorithmParameterSpec iv = null;
	 
	 private Key key = null; 

	 private Cipher encodeCipher = null;
	 private Cipher decodeCipher = null;
	 
	 private Base64DesEncrypt() throws Exception {
		 DESKeySpec keySpec = new DESKeySpec(DES_KEY.getBytes("UTF-8"));
		 iv = new IvParameterSpec(DES_IV);
		 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		 key = keyFactory.generateSecret(keySpec);
		 encodeCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		 encodeCipher.init(Cipher.ENCRYPT_MODE, key, iv);
		 decodeCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		 decodeCipher.init(Cipher.DECRYPT_MODE, key, iv);
	 }
	 	 
	 public byte[] encode(byte[] data) throws Exception {
		 byte[] pasByte = encodeCipher.doFinal(data); 
		 return Base64.encodeBase64(pasByte);  
	 }  

	 public byte[] decode(byte[] data) throws Exception { 
		 byte[] pasByte = decodeCipher.doFinal(Base64.decodeBase64(data));  
		 return pasByte;
	 } 
	 
	 public static Base64DesEncrypt getInstance() throws Exception {
		 if (inst == null) {
			 inst = new Base64DesEncrypt();
		 }
		 return inst;
	 }
	 
	 
}
